#include "KSADEventAction.hh"
#include "KSADHitsCollection.hh"
#include "KSADHit.hh"
#include "KSADGlobals.hh"
#include "G4HCofThisEvent.hh"
#include "G4Event.hh"
#include "G4SDManager.hh"
#include "G4ThreeVector.hh"
#include "TApplication.h"
#include "TFile.h"
#include "TH3D.h"

KSADEventAction::KSADEventAction()
{
	;
}

KSADEventAction::~KSADEventAction(){;}

void KSADEventAction::BeginOfEventAction(const G4Event*)
{
	;
}

void KSADEventAction::EndOfEventAction(const G4Event* event)
{
	G4HCofThisEvent* hcc = event->GetHCofThisEvent();
	KSADHitsCollection* hc = (KSADHitsCollection*)(hcc->GetHC(0));

	if(dataFilePath != "")
	{	
		if(gFile) gFile->Close();
		gFile->Open(dataFilePath,"recreate");
	}
	else if(globalH3) globalH3->Delete();

	int binDimension = 1.8*m/crystalSize;
	double timeLength = 100*ns;
	int timeBinDimension = timeLength/timeRes;
	TH3D* h3 = new TH3D("KSADh3","KSADh3",binDimension,-.6,.6,binDimension,-.6,.6,timeBinDimension,0,timeLength/ns);

	for(int l = 0;l < (int)hc->GetSize();l++)
	{
		KSADHit* hit = (KSADHit*)(hc->GetHit(l));
		G4ThreeVector hitPos = hit->GetPosition();
		double xPos = hitPos.x();
		double yPos = hitPos.y();
		double time = hit->GetTime();
		double weight = hit->GetEnergy();
		h3->Fill(xPos/m,yPos/m,time/ns,weight/MeV);
	}

	if(dataFilePath != "")
	{
		h3->Write();
		gFile->Close();
	}
	else globalH3 = h3;
}
